/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.dorm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.core.enums.BizDataTypeEnum;
import vip.xiaonuo.biz.modular.dorm.entity.Dorm;
import vip.xiaonuo.biz.modular.dorm.mapper.DormMapper;
import vip.xiaonuo.biz.modular.dorm.param.DormAddParam;
import vip.xiaonuo.biz.modular.dorm.param.DormEditParam;
import vip.xiaonuo.biz.modular.dorm.param.DormIdParam;
import vip.xiaonuo.biz.modular.dorm.param.DormPageParam;
import vip.xiaonuo.biz.modular.dorm.service.DormService;
import vip.xiaonuo.biz.modular.repair.entity.RepairApply;
import vip.xiaonuo.biz.modular.repair.service.RepairApplyService;
import vip.xiaonuo.biz.modular.repairitem.entity.RepairItem;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.sys.api.SysRoleApi;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 维修宿舍楼Service接口实现类
 *
 * @author chbzheng
 * @date  2023/06/12 19:45
 **/
@Service
public class DormServiceImpl extends ServiceImpl<DormMapper, Dorm> implements DormService {

    @Override
    public Page<Dorm> page(DormPageParam dormPageParam) {
        QueryWrapper<Dorm> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(dormPageParam.getCategory())) {
            queryWrapper.lambda().eq(Dorm::getCategory, dormPageParam.getCategory());
        }
        if(ObjectUtil.isNotEmpty(dormPageParam.getCode())) {
            queryWrapper.lambda().like(Dorm::getCode, dormPageParam.getCode());
        }
        if(ObjectUtil.isNotEmpty(dormPageParam.getName())) {
            queryWrapper.lambda().like(Dorm::getName, dormPageParam.getName());
        }
        if(ObjectUtil.isNotEmpty(dormPageParam.getEnable())) {
            queryWrapper.lambda().eq(Dorm::getEnable, dormPageParam.getEnable());
        }
        if(ObjectUtil.isAllNotEmpty(dormPageParam.getSortField(), dormPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(dormPageParam.getSortOrder());
            queryWrapper.orderBy(true, dormPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(dormPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(Dorm::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    public static final String DORM_CACHE_ALL_KEY = "biz-dorm:all";

    @Resource
    private CommonCacheOperator commonCacheOperator;
    @Resource
    private RepairApplyService repairApplyService;


    @Resource
    private SysRoleApi sysRoleApi;


    @Override
    public List<Tree<String>> tree() {
        // 获取所有机构
        List<Dorm> allOrgList = this.list();
        List<TreeNode<String>> treeNodeList = allOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(),
                        bizOrg.getName(), bizOrg.getSortCode()).setExtra(JSONUtil.parseObj(bizOrg)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DormAddParam bizOrgAddParam) {
        //DormCategoryEnum.validate(bizOrgAddParam.getCategory());
        // 校验数据范围
        /*
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(bizOrgAddParam.getParentId())) {
                throw new CommonException("您没有权限在该机构下增加机构，机构id：{}", bizOrgAddParam.getParentId());
            }
        } else {
            throw new CommonException("您没有权限增加机构");
        }*/
        Dorm bizOrg = BeanUtil.toBean(bizOrgAddParam, Dorm.class);

        // 重复名称
        boolean repeatName = this.count(new LambdaQueryWrapper<Dorm>().eq(Dorm::getParentId, bizOrg.getParentId())
                .eq(Dorm::getName, bizOrg.getName())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级类型，名称为：{}", bizOrg.getName());
        }
        bizOrg.setCode(RandomUtil.randomString(10));
        this.save(bizOrg);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.DORM.getValue(), JSONUtil.createArray().put(bizOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DormEditParam bizOrgEditParam) {
        //DormCategoryEnum.validate(bizOrgEditParam.getCategory());
        Dorm bizOrg = this.queryEntity(bizOrgEditParam.getId());
        /*
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(bizOrg.getId())) {
                throw new CommonException("您没有权限编辑该机构，机构id：{}", bizOrg.getId());
            }
            if(!loginUserDataScope.contains(bizOrg.getParentId())) {
                throw new CommonException("您没有权限编辑该机构下的机构，机构id：{}", bizOrg.getParentId());
            }
        } else {
            throw new CommonException("您没有权限编辑该机构，机构id：{}", bizOrg.getId());
        }*/
        BeanUtil.copyProperties(bizOrgEditParam, bizOrg);
        boolean repeatName = this.count(new LambdaQueryWrapper<Dorm>().eq(Dorm::getParentId, bizOrg.getParentId())
                .eq(Dorm::getName, bizOrg.getName()).ne(Dorm::getId, bizOrg.getId())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", bizOrg.getName());
        }
        List<Dorm> originDataList = this.list();
        boolean errorLevel = this.getChildListById(originDataList, bizOrg.getId(), true).stream()
                .map(Dorm::getId).collect(Collectors.toList()).contains(bizOrg.getParentId());
        if(errorLevel) {
            throw new CommonException("不可选择上级机构：{}", this.getById(originDataList, bizOrg.getParentId()).getName());
        }
        this.updateById(bizOrg);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(BizDataTypeEnum.DORM.getValue(), JSONUtil.createArray().put(bizOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DormIdParam> bizOrgIdParamList) {
        List<String> orgIdList = CollStreamUtil.toList(bizOrgIdParamList, DormIdParam::getId);
        if(ObjectUtil.isNotEmpty(orgIdList)) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(orgIdList)) {
                    throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
                }
            } else {
                throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
            }
            List<Dorm> allOrgList = this.list();
            // 获取所有子机构
            List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
            orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
                    .map(Dorm::getId).collect(Collectors.toList())));
            // 机构下有人不能删除（直属机构）

            boolean hasOrgUser = repairApplyService.count(new LambdaQueryWrapper<RepairApply>().in(RepairApply::getDormitoryId, toDeleteOrgIdList)) > 0;
            if(hasOrgUser) {
                throw new CommonException("请先删除机构下的人员");
            }
            // 机构下有人不能删除（兼任机构）


            // 执行删除
            this.removeByIds(toDeleteOrgIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(BizDataTypeEnum.DORM.getValue(), toDeleteOrgIdList);
        }
    }

    @Override
    public Dorm detail(DormIdParam bizOrgIdParam) {
        return this.queryEntity(bizOrgIdParam.getId());
    }

    @Override
    public Dorm queryEntity(String id) {
        Dorm bizOrg = this.getById(id);
        if(ObjectUtil.isEmpty(bizOrg)) {
            throw new CommonException("机构不存在，id值为：{}", id);
        }
        return bizOrg;
    }

    @Override
    public List<Dorm> getCachedAllDormList() {
        // 从缓存中取
        Object cacheValue = commonCacheOperator.get(DORM_CACHE_ALL_KEY);
        if(ObjectUtil.isNotEmpty(cacheValue)) {
            return JSONUtil.toList(JSONUtil.parseArray(cacheValue), Dorm.class);
        }
        List<Dorm> orgList = this.list(new LambdaQueryWrapper<Dorm>().orderByAsc(Dorm::getSortCode));
        if(ObjectUtil.isNotEmpty(orgList)) {
            // 更新到缓存
            commonCacheOperator.put(DORM_CACHE_ALL_KEY, JSONUtil.toJsonStr(orgList));
        }
        return orgList;
    }

    @Override
    public String getDormIdByFullNameWithCreate(String orgFullName) {
        List<Dorm> cachedAllOrgList = this.getCachedAllDormList();
        List<Tree<String>> treeList = TreeUtil.build(cachedAllOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(), bizOrg.getName(), bizOrg.getSortCode()))
                .collect(Collectors.toList()), "0");
        return findDormIdByName("0", StrUtil.split(orgFullName, StrUtil.DASHED).iterator(), cachedAllOrgList, treeList);
    }

    public String findDormIdByName(String parentId, Iterator<String> iterator, List<Dorm> cachedAllOrgList, List<Tree<String>> treeList) {
        String orgName = iterator.next();
        if(ObjectUtil.isNotEmpty(treeList)) {
            List<Tree<String>> findList = treeList.stream().filter(tree -> tree.getName().equals(orgName)).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(findList)) {
                if(iterator.hasNext()) {
                    return findDormIdByName(findList.get(0).getId(), iterator, cachedAllOrgList, findList.get(0).getChildren());
                } else {
                    return findList.get(0).getId();
                }
            }
        }
        String orgId = this.doCreateDorm(parentId, orgName, cachedAllOrgList);
        if(iterator.hasNext()) {
            return findDormIdByName(orgId, iterator, cachedAllOrgList, CollectionUtil.newArrayList());
        } else {
            return orgId;
        }
    }

    /**
     * 执行创建机构
     *
     * @author xuyuxiang
     * @date 2023/3/8 9:38
     **/
    public String doCreateDorm(String parentId, String orgName, List<Dorm> cachedAllOrgList) {
        //创建该机构
        Dorm bizOrg = new Dorm();
        bizOrg.setName(orgName);
        bizOrg.setCode(RandomUtil.randomString(10));
        bizOrg.setParentId(parentId);
        //bizOrg.setCategory(parentId.equals("0")?DormCategoryEnum.COMPANY.getValue():DormCategoryEnum.DEPT.getValue());
        bizOrg.setSortCode(99);
        this.save(bizOrg);
        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(bizOrg));
        // 将该机构加入缓存
        cachedAllOrgList.add(bizOrg);
        // 更新缓存
        commonCacheOperator.put(DORM_CACHE_ALL_KEY, cachedAllOrgList);
        return bizOrg.getId();
    }

    /* ====机构部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> dormTreeSelector() {
        LambdaQueryWrapper<Dorm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(Dorm::getId, loginUserDataScope);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(Dorm::getSortCode);
        List<Dorm> bizOrgList = this.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = bizOrgList.stream().map(bizOrg ->
                new TreeNode<>(bizOrg.getId(), bizOrg.getParentId(), bizOrg.getName(), bizOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    /* ====以下为各种递归方法==== */

    public List<Dorm> getParentAndChildListById(List<Dorm> originDataList, String id, boolean includeSelf) {
        List<Dorm> parentListById = this.getParentListById(originDataList, id, false);
        List<Dorm> childListById = this.getChildListById(originDataList, id, true);
        parentListById.addAll(childListById);
        return parentListById;
    }

    public List<Dorm> getChildListById(List<Dorm> originDataList, String id, boolean includeSelf) {
        List<Dorm> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(originDataList, id, resultList);
        if(includeSelf) {
            Dorm self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    public List<Dorm> getParentListById(List<Dorm> originDataList, String id, boolean includeSelf) {
        List<Dorm> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(originDataList, id, resultList);
        if(includeSelf) {
            Dorm self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    public void execRecursionFindChild(List<Dorm> originDataList, String id, List<Dorm> resultList) {
        originDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(originDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<Dorm> originDataList, String id, List<Dorm> resultList) {
        originDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                Dorm parent = this.getById(originDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(originDataList, item.getParentId(), resultList);
            }
        });
    }

    public Dorm getById(List<Dorm> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, Dorm::getId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }

    public Dorm getParentById(List<Dorm> originDataList, String id) {
        Dorm self = this.getById(originDataList, id);
        return ObjectUtil.isNotEmpty(self)?self:this.getById(originDataList, self.getParentId());
    }

    public Dorm getChildById(List<Dorm> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, Dorm::getParentId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }
}
